package com.iwdm.latex;

import android.content.ContextWrapper;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;

import static com.iwdm.latex.Utils.getLocalBitmap;

public class SelectActivity extends AppCompatActivity implements TakePhoto.TakeResultListener, InvokeListener {

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private Uri imageUri;
    private ImageView imageView;
    private String originalPath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select);
        imageView = findViewById(R.id.img);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        //配置图片压缩
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(500 * 1024) //500K
                .setMaxPixel(1000) //1000px
                .create();
        takePhoto.onEnableCompress(config, true);//true是否显示提示压缩dialog
        return takePhoto;
    }

    //拍照
    public void pick(View view) {
        imageUri = getImageCropUri();
        //从相册中选取图片并裁剪
        int size = Math.min(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
        CropOptions cropOptions = new CropOptions.Builder().setOutputX(size).setOutputX(size).setWithOwnCrop(false).create();
        takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
        //从相册中选取不裁剪
        // takePhoto.onPickFromGallery();

    }

    //选择图片
    public void photograph(View view) {
        imageUri = getImageCropUri();
        int size = Math.min(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
        CropOptions cropOptions = new CropOptions.Builder().setOutputX(size).setOutputX(size).setWithOwnCrop(false).create();
        //拍照并裁剪
        takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
        //仅仅拍照不裁剪
        // takePhoto.onPickFromCapture(imageUri);
    }

    @Override
    public void takeSuccess(TResult result) {
        imageView.setImageBitmap(getLocalBitmap(result.getImage().getCompressPath()));
        //在此我用的是原图路径，可选压缩路径
        originalPath = result.getImage().getOriginalPath();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(this, "选择失败" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeCancel() {
        Toast.makeText(this, "取消选择", Toast.LENGTH_SHORT).show();

    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File file = new File(directory, System.currentTimeMillis() + ".jpg");

        // File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }


    public void commit(View view) {
        if (TextUtils.isEmpty(originalPath)) {
            Toast.makeText(this, "非法操作", Toast.LENGTH_SHORT).show();
            return;

        }
        startActivity(new Intent(this, MainActivity.class).putExtra("originalPath", originalPath));
    }
}
